#!/usr/bin/env python3
# coding: utf-8
"""
2025-11-05 检查项目方案编辑界面
"""

from PySide6.QtCore import Slot, QSize
from PySide6.QtGui import QAction, QKeySequence,QIntValidator, QTextCursor, QDoubleValidator   
from PySide6.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QPushButton, QWidget,QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QLabel,QCheckBox,QTextEdit,QGroupBox,QComboBox,QDateTimeEdit,QTimeEdit,QGridLayout
from PySide6.QtCore import Qt, QModelIndex,QMetaObject,Q_ARG,QDateTime,QTime
from PySide6.QtGui import QGuiApplication, QCloseEvent
## from PySide6.QtCore.Qt import 
# from top.wardyan.core.widges.controlls import WTextEdit as QLineEdit

##from PySide6.QtCore import WindowState

## from top.wardyan.core.utils import winformutils
from top.wardyan.core.action.baseaction import WMainWindow,WQdialog
from top.wardyan.core.vo.vos import *
from top.wardyan.core.widges.tables import WTableView

##from warningmain import *
from top.wardyan.core.wdb.core.DBPool import POOL

from top.wardyan.core.vo.vos import *
from top.wardyan.core.wdb.core.db import *
from config import Config
from top.wardyan.core.sqlite import sqliteconfigs

import threading
import time
import re
import sys

from apscheduler.schedulers.background import BackgroundScheduler
from top.wardyan.core.utils.common import *
from top.wardyan.core.wdb.core.dic import *
import uuid

from top.wardyan.projects.checktool_manager.main.checktool_manager_const import *


SQL_FIND = "SELECT * FROM yt_checkplan WHERE sID = %s"
SQL_FIND_CHECK_ITEMS = "SELECT * FROM yt_check WHERE sStatus >= 5 ORDER BY sID"
SQL_FIND_SELECTED_ITEMS = "SELECT rCheck_ID FROM yt_checkplan_item WHERE mID = %s"



        

class ChecktoolCheckplanEditShell (WQdialog) :
        
    def __init__(self, checkplanid) -> None:
        ##global cn
        super().__init__("ChecktoolCheckplanEditShell")
        self.editable = False
        self.checkplanid = checkplanid
        self.table : WTableView = None  # type: ignore
        self.check_items = []  # 存储所有可选的检查项目
        self.selected_items = set()  # 存储已选择的检查项目ID
        self.check_item_widgets = {}  # 存储检查项目对应的复选框
        self.main()
        ## self.refreshTable()
        self.load()
        # 初始化后更新检查项目复选框的可编辑状态
        self.update_check_item_editable_state()
    def button_click_add(self) :
        pass


    def handle_bind(self, isDeBind : bool = False):
        if isDeBind :
            try :
                self.xNameLineEdit.textChanged.disconnect(self.on_input_changed)
                self.xNoteTextEdit.textChanged.disconnect(self.on_input_changed)
            except BaseException as e :
                pass
        else : 
            self.xNameLineEdit.textChanged.connect(self.on_input_changed)
            self.xNoteTextEdit.textChanged.connect(self.on_input_changed)
            
    def on_input_changed(self):
        self.btnSave.setEnabled(True)
        self.btnEdit.setEnabled(False)
        self.btnAudit.setEnabled(False)
        self.btnAdd.setEnabled(False)
        self.btnDel.setEnabled(False)

    def on_input_inited(self) :
        if self.checkplanid is not None and self.checkplanid > 0 :
            self.btnSave.setEnabled(False)
            self.btnEdit.setEnabled(True)
            self.btnAudit.setEnabled(True)
            self.btnAdd.setEnabled(True)
            self.btnDel.setEnabled(False)
        else :
            self.btnSave.setEnabled(True)
            self.btnEdit.setEnabled(False)
            self.btnAudit.setEnabled(False)
            self.btnAdd.setEnabled(False)
            self.btnDel.setEnabled(False)

        self.xNameLineEdit.textChanged.connect(self.on_input_changed)
        self.xNoteTextEdit.textChanged.connect(self.on_input_changed)


    def _add_form_row_two(self, layout: QGridLayout, label1_text: str, widget1: QWidget,
                        label2_text: str, widget2: QWidget, label_width: int):
        row = layout.rowCount()

        label1 = QLabel(label1_text)
        label1.setFixedWidth(label_width)
        layout.addWidget(label1, row, 0)
        layout.addWidget(widget1, row, 1)

        label2 = QLabel(label2_text)
        label2.setFixedWidth(label_width)
        layout.addWidget(label2, row, 2)
        layout.addWidget(widget2, row, 3)

    def _add_form_row_two_no_label(self, layout: QGridLayout, widget1: QWidget,
                                 widget2: QWidget):
        row = layout.rowCount()
        # 添加一些空白标签以保持布局一致
        empty_label1 = QLabel("")
        layout.addWidget(empty_label1, row, 0)
        layout.addWidget(widget1, row, 1)

        empty_label2 = QLabel("")
        layout.addWidget(empty_label2, row, 2)
        layout.addWidget(widget2, row, 3)

    def main(self) :

        HEIGHT = 40
        layout : QVBoxLayout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignVCenter)
        self.setLayout(layout)
        
        

        ## 按钮: 搜索 新增
        topwidget : QWidget = QWidget()
        ##topwidget.setFixedHeight(100)
        layout.addWidget(topwidget)
        topwidget.setFixedHeight(50)
        
        # 设置背景颜色
        #topwidget.setStyleSheet("background-color: #ffff00;padding:0;margin:0;")  # 你可以将 #f0f0f0 替换为你想要的颜色代码

        toplayout : QHBoxLayout = QHBoxLayout()
        toplayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        ##self.setLayout(layout)
        ##layout.addWidget(toplayout)
        topwidget.setLayout(toplayout)

        
        
        self.btnDel : QPushButton = QPushButton("删除")
        self.btnDel.setFixedHeight(HEIGHT)
        self.btnDel.setFixedWidth(150)
        self.btnDel.clicked.connect(self.btn_click_del_data)
        toplayout.addWidget(self.btnDel)

        
        
        self.btnEdit : QPushButton = QPushButton("编辑")
        self.btnEdit.setFixedHeight(HEIGHT)
        self.btnEdit.setFixedWidth(150)
        self.btnEdit.clicked.connect(self.btn_click_edit_data)
        toplayout.addWidget(self.btnEdit)


        ### 
        self.btnSave : QPushButton = QPushButton("保存")
        self.btnSave.setFixedHeight(HEIGHT)
        self.btnSave.setFixedWidth(150)
        self.btnSave.clicked.connect(self.btn_click_save_data)
        self.btnSave.setDefault(True)
        toplayout.addWidget(self.btnSave)
        

        self.btnAudit : QPushButton = QPushButton("审核")
        self.btnAudit.setFixedHeight(HEIGHT)
        self.btnAudit.setFixedWidth(150)
        self.btnAudit.clicked.connect(self.btn_click_audit_data)
        toplayout.addWidget(self.btnAudit)



        self.btnAdd : QPushButton = QPushButton("新增")
        self.btnAdd.setFixedHeight(HEIGHT)
        self.btnAdd.setFixedWidth(150)
        self.btnAdd.clicked.connect(self.button_click_add)
        self.btnAdd.setVisible(False)
        toplayout.addWidget(self.btnAdd)


        ###################

        ctrlw : QWidget = QWidget()
        ctrllayout : QHBoxLayout = QHBoxLayout()
        ctrlw.setLayout(ctrllayout)
        layout.addWidget(ctrlw)


        ctrllayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        

        # 获取已有的 QVBoxLayout 主布局
        main_layout = self.layout()  # type: ignore

        # 创建一个 QGroupBox 容器来包含表单内容
        form_group_box = QGroupBox("检查项目方案编辑")
        form_grid_layout = QGridLayout()
        form_grid_layout.setColumnStretch(0, 1)  # 标签列比例
        form_grid_layout.setColumnStretch(1, 3)  # 控件列比例
        form_grid_layout.setColumnStretch(2, 1)  # 标签列比例
        form_grid_layout.setColumnStretch(3, 3)  # 控件列比例

        label_width = 120  # 所有标签统一宽度

        # s开头的字段不需要显示，但需要创建以便在load_data中使用
        # sID 输入框
        self.sIDLineEdit = QLineEdit()
        self.sIDLineEdit.setMaxLength(100)
        self.sIDLineEdit.setReadOnly(True)
        self.sIDLineEdit.setFixedHeight(HEIGHT)
        self.sIDLineEdit.setVisible(False)  # 隐藏s开头的字段

        # xName 输入框
        self.xNameLineEdit = QLineEdit()
        self.xNameLineEdit.setMaxLength(100)
        self.xNameLineEdit.setFixedHeight(HEIGHT)

        # 名称输入框占满一行
        self._add_form_row(form_grid_layout, "名称:", self.xNameLineEdit, label_width)

        # xNote 多行文本框
        self.xNoteTextEdit = QTextEdit()
        self.xNoteTextEdit.setMaximumHeight(80)
        
        # 备注输入框占满一行
        self._add_form_row(form_grid_layout, "备注:", self.xNoteTextEdit, label_width)
        
        # 隐藏所有以s开头的字段
        # sStatus 输入框
        self.sStatusLineEdit = QLineEdit()
        self.sStatusLineEdit.setValidator(QIntValidator())  # 限制只能输入整数
        self.sStatusLineEdit.setFixedHeight(HEIGHT)
        self.sStatusLineEdit.setVisible(False)  # 隐藏s开头的字段

        # sVersion 输入框
        self.sVersionLineEdit = QLineEdit()
        self.sVersionLineEdit.setValidator(QIntValidator())  # 限制只能输入整数
        self.sVersionLineEdit.setFixedHeight(HEIGHT)
        self.sVersionLineEdit.setVisible(False)  # 隐藏s开头的字段

        # sOwner 输入框
        self.sOwnerLineEdit = QLineEdit()
        self.sOwnerLineEdit.setMaxLength(100)
        self.sOwnerLineEdit.setFixedHeight(HEIGHT)
        self.sOwnerLineEdit.setVisible(False)  # 隐藏s开头的字段

        # sAuditor 输入框
        self.sAuditorLineEdit = QLineEdit()
        self.sAuditorLineEdit.setMaxLength(100)
        self.sAuditorLineEdit.setFixedHeight(HEIGHT)
        self.sAuditorLineEdit.setVisible(False)  # 隐藏s开头的字段

        # sEditor 输入框
        self.sEditorLineEdit = QLineEdit()
        self.sEditorLineEdit.setMaxLength(100)
        self.sEditorLineEdit.setFixedHeight(HEIGHT)
        self.sEditorLineEdit.setVisible(False)  # 隐藏s开头的字段

        # sCreateTime 日期时间选择
        self.sCreateTimeEdit = QDateTimeEdit()
        self.sCreateTimeEdit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        self.sCreateTimeEdit.setCalendarPopup(True)  # 启用下拉日历选择
        self.sCreateTimeEdit.setFixedHeight(HEIGHT)
        self.sCreateTimeEdit.setVisible(False)  # 隐藏s开头的字段

        # sLastUpdate 日期时间选择
        self.sLastUpdateEdit = QDateTimeEdit()
        self.sLastUpdateEdit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        self.sLastUpdateEdit.setCalendarPopup(True)  # 启用下拉日历选择
        self.sLastUpdateEdit.setFixedHeight(HEIGHT)
        self.sLastUpdateEdit.setVisible(False)  # 隐藏s开头的字段

        form_group_box.setLayout(form_grid_layout)
        main_layout.insertWidget(1, form_group_box)  # type: ignore

        # 创建检查项目选择区域
        check_items_group_box = QGroupBox("检查项目选择")
        check_items_layout = QVBoxLayout()
        check_items_group_box.setLayout(check_items_layout)
        main_layout.addWidget(check_items_group_box)  # type: ignore

        # 创建一个滚动区域来容纳检查项目
        from PySide6.QtWidgets import QScrollArea
        self.checkItemsScrollArea = QScrollArea()
        self.checkItemsScrollArea.setWidgetResizable(True)  # 允许滚动区域自动调整大小
        self.checkItemsScrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)  # 禁用水平滚动条
        self.checkItemsScrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)  # 需要时显示垂直滚动条
        
        self.checkItemsWidget = QWidget()
        self.checkItemsLayout = QVBoxLayout()
        self.checkItemsWidget.setLayout(self.checkItemsLayout)
        self.checkItemsScrollArea.setWidget(self.checkItemsWidget)
        check_items_layout.addWidget(self.checkItemsScrollArea)

        ## 内容变更回让保存可用
        


    def _add_form_row(self, layout: QGridLayout, label_text: str, widget: QWidget, label_width: int):
        row = layout.rowCount()
        label = QLabel(label_text)
        label.setFixedWidth(label_width)
        layout.addWidget(label, row, 0)
        layout.addWidget(widget, row, 1, 1, 3)
        
    def load(self) :
        # 加载检查项目列表
        self.load_check_items()
        
        if self.checkplanid is not None and self.checkplanid > 0 :
            datas = query(sql=SQL_FIND, params=(self.checkplanid,), config=MYCONFIG)
            if datas is not None and len(datas) > 0 :
                data = datas[0]
                self.load_data(data)
        else:
            # 新增界面
            self.set_default_values()
        self.on_input_inited()
        
    def set_default_values(self):
        """
        在新增界面中设置默认值
        """
        # 新增界面默认设置为可编辑
        self.editable = True
        # 更新检查项目复选框的可编辑状态
        self.update_check_item_editable_state()
        
    def load_check_items(self):
        """
        从数据库加载所有已审核的检查项目到界面
        """
        try:
            # 查询所有已审核的检查项目
            items = query(sql=SQL_FIND_CHECK_ITEMS, config=MYCONFIG)
            if items is not None:
                self.check_items = items
                
                # 查询当前方案已选择的检查项目
                if self.checkplanid is not None and self.checkplanid > 0:
                    selected_datas = query(sql=SQL_FIND_SELECTED_ITEMS, params=(self.checkplanid,), config=MYCONFIG)
                    self.selected_items = {data["rCheck_ID"] for data in selected_datas} if selected_datas else set()
                
                # 创建检查项目复选框
                self.create_check_item_widgets()
        except Exception as e:
            print(f"加载检查项目失败: {e}")
        
    def clear_check_items_layout(self):
        """
        清空检查项目布局
        """
        # 删除所有子控件和子布局
        while self.checkItemsLayout.count():
            child = self.checkItemsLayout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()
            elif child.layout():
                # 递归删除子布局中的控件
                sub_layout = child.layout()
                while sub_layout.count():
                    sub_child = sub_layout.takeAt(0)
                    if sub_child.widget():
                        sub_child.widget().deleteLater()
                child.layout().deleteLater()
        self.check_item_widgets.clear()
        
    def create_check_item_widgets(self):
        """
        创建检查项目复选框控件
        """
        # 清空现有的检查项目布局
        self.clear_check_items_layout()
        
        # 如果没有检查项目，直接返回
        if not self.check_items:
            return
        
        # 每行显示2个检查项目
        row_layout = None
        for i, item in enumerate(self.check_items):
            # 每行两个项目
            if i % 2 == 0:
                row_layout = QHBoxLayout()
                self.checkItemsLayout.addLayout(row_layout)
            
            # 创建复选框
            check_id = item["sID"]
            check_name = item["xName"] or f"检查项目{check_id}"
            checkbox = QCheckBox(check_name)
            checkbox.setChecked(check_id in self.selected_items)
            
            # 连接复选框状态改变信号到输入变化处理方法
            checkbox.stateChanged.connect(self.on_check_item_changed)
            
            # 只有已审核的项目才能操作
            if item.get("sStatus", 0) >= 5:
                checkbox.setEnabled(self.editable)
            else:
                checkbox.setEnabled(False)
            
            # 保存复选框引用
            self.check_item_widgets[check_id] = checkbox
            
            # 添加到行布局
            if row_layout:
                row_layout.addWidget(checkbox)
        
        # 添加伸展因子使布局美观
        if row_layout:
            # 先确保最后一行有伸展因子
            row_layout.addStretch()
        else:
            # 如果没有任何项目，也添加一个空的伸展因子
            self.checkItemsLayout.addStretch()
            
    def on_check_item_changed(self):
        """
        处理检查项目复选框状态改变事件
        """
        self.on_input_changed()
        
    def load_data(self, data: dict):
        """
        加载数据到编辑界面
        :param data: 字典格式的数据，如从数据库查询得到
        """
        self.handle_bind(True)
        self.data = data
        self.sIDLineEdit.setText(str(data.get("sID", "")))
        self.xNameLineEdit.setText(data.get("xName", ""))
        self.xNoteTextEdit.setPlainText(data.get("xNote", ""))
        
        # 日期时间字段处理
        create_time = data.get("sCreateTime")
        if create_time:
            self.sCreateTimeEdit.setDateTime(QDateTime.fromString(str(create_time), "yyyy-MM-dd HH:mm:ss"))
            
        last_update = data.get("sLastUpdate")
        if last_update:
            self.sLastUpdateEdit.setDateTime(QDateTime.fromString(str(last_update), "yyyy-MM-dd HH:mm:ss"))
            
        self.sStatusLineEdit.setText(str(data.get("sStatus", "")))
        self.sVersionLineEdit.setText(str(data.get("sVersion", "")))
        self.sOwnerLineEdit.setText(data.get("sOwner", ""))
        self.sAuditorLineEdit.setText(data.get("sAuditor", ""))
        self.sEditorLineEdit.setText(data.get("sEditor", ""))

        ## 设置是否可以修改
        # 以s开头的字段不允许编辑且已隐藏
        # 日期时间类型字段只显示
        
        # 设置可编辑字段
        self.xNameLineEdit.setReadOnly(not self.editable)
        self.xNoteTextEdit.setReadOnly(not self.editable)
        
        # 重新加载检查项目（因为需要根据editable状态设置复选框）
        # 注意：这里不需要重新加载检查项目，因为load()方法中已经加载过了

        ## 判断按钮
        self.on_input_inited()
        self.handle_bind(False)

        s : int = int(data.get("sStatus", 0))
        if s > 2 :
            self.btnAudit.setText("已审核")
            self.btnAudit.setEnabled(False)
            self.btnAudit.setDisabled(True)
        else :
            self.btnAudit.setText("待审核")
            self.btnAudit.setEnabled(True)

    
    
    def btn_click_del_data(self) :
        ## 先检查下能不能删
        self.editable = True
        params = (self.checkplanid,)
        try:
            # 先删除明细表中的记录
            exec(sql="DELETE FROM yt_checkplan_item WHERE mID = %s", params=params, config=MYCONFIG)
            # 再删除主表记录
            exec(sql="DELETE FROM yt_checkplan WHERE sID = %s", params=params, config=MYCONFIG)
            QMessageBox.information(self, "删除成功", "数据删除成功！")
            self.close()
        except Exception as e:
            QMessageBox.warning(self, "删除失败", f"删除数据时发生错误：{str(e)}")

    def btn_click_edit_data(self) :
        self.editable = True
        params = (self.checkplanid,)
        exec(sql="UPDATE yt_checkplan SET sStatus = 2, sVersion = ISNULL(sVersion, 0) + 1, sLastUpdate = GETDATE() WHERE sID = %s", params=params, config=MYCONFIG)
        self.on_input_inited()
        self.load()
        self.btnEdit.setDisabled(True)
        self.btnDel.setEnabled(True)
        # 更新检查项目复选框的可编辑状态
        self.update_check_item_editable_state()
        
    def update_check_item_editable_state(self):
        """
        更新检查项目复选框的可编辑状态
        """
        for check_id, checkbox in self.check_item_widgets.items():
            # 查找对应的检查项目数据
            item = next((item for item in self.check_items if item["sID"] == check_id), None)
            if item and item.get("sStatus", 0) >= 5:
                checkbox.setEnabled(self.editable)
            else:
                checkbox.setEnabled(False)

    def btn_click_audit_data(self) :
        self.editable = False
        params = (self.checkplanid,)
        exec(sql="UPDATE yt_checkplan SET sStatus = 5, sVersion = ISNULL(sVersion, 0) + 1, sLastUpdate = GETDATE() WHERE sID = %s", params=params, config=MYCONFIG)
        QMessageBox.information(self, "审核成功", "数据审核成功！")
        self.on_input_inited()
        self.load()
        # 更新检查项目复选框的可编辑状态
        self.update_check_item_editable_state()
        
    def btn_click_save_data(self) -> None:
        """
        保存数据
        """
        # 验证必填字段
        if not self.xNameLineEdit.text().strip():
            QMessageBox.warning(self, "提示", "名称不能为空！")
            return

        # 验证文本框长度
        if len(self.xNameLineEdit.text().strip()) > 100:
            QMessageBox.warning(self, "提示", "名称长度不能超过100个字符！")
            return
            
        if len(self.xNoteTextEdit.toPlainText().strip()) > 500:
            QMessageBox.warning(self, "提示", "备注长度不能超过500个字符！")
            return

        # 准备参数
        x_name = self.xNameLineEdit.text().strip()
        x_note = self.xNoteTextEdit.toPlainText().strip()
        
        try:
            # 根据是否有sID判断是新增还是修改
            if self.checkplanid is not None and self.checkplanid > 0 :
                # 修改
                sql = """UPDATE dbo.yt_checkplan 
    SET xName = %s, xNote = %s,
        sVersion = ISNULL(sVersion, 0) + 1, sLastUpdate = GETDATE()
    WHERE sID = %s"""
                params = (x_name, x_note, self.checkplanid)
                exec(sql, params, MYCONFIG)
            else :
                # 新增
                self.checkplanid = self.get_next_id()
                sql = """INSERT INTO dbo.yt_checkplan (
	sID, xDateTime, xName, xNote, sStatus, sVersion, 
	sCreateTime, sLastUpdate, sOwner, sAuditor, sEditor
)
VALUES (
	%s, GETDATE(), %s, %s, 2, 1, 
	GETDATE(), GETDATE(), %s, %s, %s
)"""
                # 获取当前用户信息（这里简化处理，实际应该从系统中获取）
                current_user = "admin"
                params = (self.checkplanid, x_name, x_note, current_user, current_user, current_user)
                exec(sql, params, MYCONFIG)
                
            # 保存检查项目选择
            self.save_check_item_selection()
                
            ## 提示保存OK
            self.editable = False
            QMessageBox.information(self, "保存成功", "数据保存成功！")
            self.load()
            # 更新检查项目复选框的可编辑状态
            self.update_check_item_editable_state()
        except Exception as e:
            QMessageBox.warning(self, "保存失败", f"保存数据时发生错误：{str(e)}")

    def save_check_item_selection(self):
        """
        保存检查项目选择
        """
        if self.checkplanid is None or self.checkplanid <= 0:
            return
            
        try:
            # 获取当前选中的检查项目
            selected_check_ids = set()
            for check_id, checkbox in self.check_item_widgets.items():
                if checkbox.isChecked():
                    selected_check_ids.add(check_id)
            
            # 获取之前选中的检查项目
            old_selected_ids = self.selected_items
            
            # 计算需要新增和删除的项目
            to_add = selected_check_ids - old_selected_ids
            to_delete = old_selected_ids - selected_check_ids
            
            # 删除取消选择的项目
            if to_delete:
                placeholders = ",".join(["%s"] * len(to_delete))
                delete_sql = f"DELETE FROM yt_checkplan_item WHERE mID = %s AND rCheck_ID IN ({placeholders})"
                delete_params = [self.checkplanid] + list(to_delete)
                exec(sql=delete_sql, params=tuple(delete_params), config=MYCONFIG)
            
            # 添加新选择的项目
            for check_id in to_add:
                insert_sql = """INSERT INTO yt_checkplan_item (mID, dID, rCheck_ID) 
                               VALUES (%s, %s, %s)"""
                # 获取下一个dID
                next_did = self.get_next_did()
                insert_params = (self.checkplanid, next_did, check_id)
                exec(sql=insert_sql, params=insert_params, config=MYCONFIG)
                
        except Exception as e:
            print(f"保存检查项目选择失败: {e}")
            raise e

    def get_next_id(self):
        """
        获取下一个可用的ID
        """
        try:
            result = query(sql="SELECT ISNULL(MAX(sID), 0) + 1 AS next_id FROM yt_checkplan", config=MYCONFIG)
            if result and len(result) > 0:
                return result[0]["next_id"]
            else:
                return 1
        except Exception as e:
            print(f"获取下一个ID失败: {e}")
            return 1
            
    def get_next_did(self):
        """
        获取下一个明细ID
        """
        try:
            result = query(sql="SELECT ISNULL(MAX(dID), 0) + 1 AS next_did FROM yt_checkplan_item", config=MYCONFIG)
            if result and len(result) > 0:
                return result[0]["next_did"]
            else:
                return 1
        except Exception as e:
            print(f"获取下一个明细ID失败: {e}")
            return 1